<template>
  <el-dialog
    class="share-dialog"
    :title="$t('portal.sharePoster')"
    :visible.sync="shareDialogVisible"
    width="800px"
  >
    <div class="share-dialog-container">
      <!-- <div class="share-dialog-container-header">
        <span>分享链接</span>
        <el-input
          class="share-setting-header-input"
          readonly
          v-model="shareLink"
        >
          <el-button
            class="share-setting-copy"
            type="primary"
            slot="append"
            @click="handleClickCopyShareUrl"
            :data-clipboard-text="shareLink"
            >复制</el-button
          >
        </el-input>
        <span class="share-seeting-header-button" @click="downloadQrcode"
          >仅下载二维码</span
        >
        <span class="share-seeting-header-button" @click="downloadPoster"
          >下载完整海报</span
        >
      </div> -->

      <div class="share-dialog-container-main">
        <!-- <h3>分享样式预览</h3> -->
        <div class="share-dialog-style-view">
          <div class="share-dialog-style-box">
            <portalShareComponent
              ref="portalShareRef"
              :config="shareForm"
              :link="shareLink"
              :door-type-id="doorTypeId"
              :appletCodeUrl="appletCodeUrl"
              @saveDownload="saveConfig(true)"
            ></portalShareComponent>
          </div>

          <div class="share-dialog-style-config" v-if="portalAuth.updateShare">
            <el-form
              :model="shareForm"
              :rules="shareRules"
              ref="shareFormRef"
              label-position="top"
            >
              <!-- <el-form-item label="分享样式">
                <el-radio-group v-model="shareForm.shareStyle">
                  <el-radio :label="1">海报</el-radio>
                  <el-radio :label="2">微信朋友</el-radio>
                  <el-radio :label="3">朋友圈</el-radio>
                </el-radio-group>
              </el-form-item> -->
              <el-form-item :label="$t('portal.posterTitle')" prop="shareTitle">
                <div class="share-form-item">
                  <el-input
                    class="share-dialog-style-textarea"
                    type="textarea"
                    v-model="shareForm.shareTitle"
                    :rows="2"
                  ></el-input>
                  <base-select-language
                    v-if="isMultiLanguage"
                    :field="titleField"
                    :defaultOption="{ formType:'text' }"
                    :maxlength="20"
                    defaultFormType="text"
                    :defaultValue="shareForm.shareTitle"
                    :defaultValueLanguage="shareForm.setting.shareTitleLanguage"
                    @save="updateTitleLanguage"
                  >
                  </base-select-language>
                </div>
              </el-form-item>

              <el-form-item :label="$t('portal.posterDescription')" prop="shareDescribe">
                <div class="share-form-item">
                  <el-input
                    class="share-dialog-style-textarea"
                    type="textarea"
                    v-model="shareForm.shareDescribe"
                    :autosize="{ minRows: 3, maxRows: 4 }"
                  ></el-input>
                  <base-select-language 
                    :field="describeField"
                    :defaultOption="{ formType:'text' }"
                    :maxlength="20"
                    defaultFormType="text"
                    :defaultValue="shareForm.shareDescribe"
                    :defaultValueLanguage="shareForm.setting.shareDescribeLanguage"
                    @save="updateDescribeLanguage"
                  >
                  </base-select-language>
                </div>
              </el-form-item>

              <el-form-item
                class="share-dialog-style-upload"
                :label="$t('portal.posterPicture')"
              >
                <el-upload
                  class="share-image-uploader"
                  action="string"
                  :before-upload="onBeforeUploadImage"
                  :http-request="uploadImagePic"
                  :show-file-list="false"
                  :limit="10000"
                  accept=".jpg,.jpeg,.png"
                >
                  <img
                    v-if="shareForm.sharePicture"
                    :src="shareForm.sharePicture"
                    class="share-style-image"
                  />
                  <i v-else class="el-icon-plus share-uploader-icon"></i>
                </el-upload>
                <!-- <span>建议图片尺寸：516*414像素</span> -->
                <span>{{ $t('portal.posterTip1', { num1: '516', num2: '414' }) }}</span>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer">
      <el-button class="share-dialog-style-button" type="primary" @click="saveConfig()">{{ $t('common.base.save')}}</el-button>
      <!-- <el-button class="share-dialog-style-button" @click="saveConfig(true)">{{ $t('portal.saveAndDownload')}}</el-button> -->
    </div>
  </el-dialog>
</template>

<script>
import { reactive, toRefs, ref, inject, watch, nextTick } from 'vue';
import Uploader from 'packages/BaseUpload/uploader';
import portalShareComponent from './portalShareComponent.vue';
/* hooks */
import { usePortalShareConfig } from '@hooks/portal/usePortalShareDialog.ts';
import { Message } from 'element-ui';
import { getShareInfoV2, saveShareInfoV2 } from '@src/api/PortalApi.ts';
import Platform from '@src/util/platform.ts';
/* constanst */
import { SAVE_SUCCESS } from '@src/model/const/Alert.ts'
import { randomString } from '@src/util/lang/string';
import i18n from '@src/locales';
import { getAttachmentIdByUrl } from 'pub-bbx-utils'

export default {
  components: {
    portalShareComponent,
  },
  props: {
    shareLink: {
      type: String,
      default: '',
    },
    tenantId: {
      type: String,
      default: '',
    },
    doorTypeId: {
      type: Number,
    },
    portalAuth: {
      type: Object,
      default: () => ({}),
    },
    appletCodeUrl: {
      type: String,
      default: '',
    },
  },
  setup(props) {
    const state = reactive({
      shareDialogVisible: false,
      shareConfig: {},
      shareRules: {
        shareTitle: [
          { required: true, message: i18n.t('portal.posterTip2'), trigger: 'blur' },
          { max: 20, message: i18n.t('portal.posterTip3', { num: 20 }), trigger: 'blur' }
        ],
        shareDescribe: [
          { required: true, message: i18n.t('portal.posterTip4'), trigger: 'blur' },
          { max: 20, message: i18n.t('portal.posterTip3', { num: 20 }), trigger: 'blur' }
        ],
      },
      shareForm: {
        id: '',
        shareStyle: 1,
        shareTitle: '',
        setting: {
          shareTitleLanguage: {},
          shareDescribeLanguage: {},
        },
        shareDescribe: '',
        sharePicture: '',
      },
      editAuth: true,
      titleField: {
        displayName: i18n.t('portal.posterTitle'),
        fieldName: "shareTitle",
        formType: "text",
        id: randomString(),
        isNull: 0,
      },
      describeField: {
        displayName: i18n.t('portal.posterDescription'),
        fieldName: "shareDescribe",
        formType: "textarea",
        id: randomString(),
        isNull: 0,
      },
      needServerDeleFiles: [], // 需要删除的服务器文件
    });

    const shareFormRef = ref(null);
    const portalShareRef = ref(null);
    const languagesList = inject('languagesList');
    const isMultiLanguage = inject('isMultiLanguage');

    const [handleClickCopyShareUrl] = usePortalShareConfig(props);

    const getPartalShareInfo = async () => {
      try {
        const params = {
          tenantId: props.tenantId,
          typeId: props.doorTypeId
        }
        const { code, data } = await getShareInfoV2(params);
        if (code != 200) return;
        nextTick(() => {
          shareFormRef.value?.resetFields();

          state.shareForm = data;
          if (state.shareForm.setting) {
            try {
              state.shareForm.setting = JSON.parse(state.shareForm.setting)
            } catch (err) {
              state.shareForm.setting = {}
            }
          }
          !state.shareForm.setting && (state.shareForm.setting = {});
          !state.shareForm.setting.shareTitleLanguage && (state.shareForm.setting.shareTitleLanguage = {});
          !state.shareForm.setting.shareDescribeLanguage && (state.shareForm.setting.shareDescribeLanguage = {});
          state.shareForm.setting.shareTitleLanguage[i18n.locale] && (state.shareForm.shareTitle = state.shareForm.setting.shareTitleLanguage[i18n.locale])
          state.shareForm.setting.shareDescribeLanguage[i18n.locale] && (state.shareForm.shareDescribe = state.shareForm.setting.shareDescribeLanguage[i18n.locale])
        })

        // Object.assign(state.shareForm, state.shareConfig);
      } catch (error) {
        console.error('getPartalShareInfo error', error);
      };
    };

    const openDialog = () => {
      state.shareDialogVisible = true;
      state.needServerDeleFiles = []
      getPartalShareInfo();
    };

    const downloadQrcode = () => {
      portalShareRef.value.downloadQrcode();
    };

    const downloadPoster = () => {
      portalShareRef.value.downloadPoster();
    };

    const onBeforeUploadImage = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        Message.error(i18n.t('product.productType.tips.tip24'));
      }
      if (!isLt2M) {
        Message.error(i18n.t('common.validate.imageLimit', { limit: '2mb' }));
      }

      return isJPG && isLt2M;
    };

    const uploadImagePic = (file) => {
      Uploader.upload(file.file, '/files/upload')
        .then((result) => {
          if (result.status !== 0) {
            Message.error(result.message);
            return;
          }
          // 存储需要删除的服务器文件
          if (state.shareForm.sharePicture) {
            const fileId = getAttachmentIdByUrl(state.shareForm.sharePicture)
            fileId && state.needServerDeleFiles.push(fileId)
          }
          let file = result.data;
          // 如果后端返回url,必须使用。如果后端不返回，需要拼接
          state.shareForm.sharePicture = file.ossUrl || file.url || `/files/get?fileId=${file.id}`;
        })
        .catch((err) => {
          console.warn(err);
        });
    };

    const updateTitleLanguage = (value) => {
      state.shareForm.shareTitle = value?.[i18n.locale];
      state.shareForm.setting.shareTitleLanguage = value;
    };

    const updateDescribeLanguage = (value) => {
      state.shareForm.shareDescribe = value?.[i18n.locale];
      state.shareForm.setting.shareDescribeLanguage = value;
    };

    const saveConfig = (isDownload = false) => {
      shareFormRef.value.validate((valid) => {
        if (valid) {
          const params = {
            typeId:props.doorTypeId,
            ...state.shareForm
          }
          params.setting = JSON.stringify(params.setting)
          if (state.needServerDeleFiles.length){
            params.deleteFiles = state.needServerDeleFiles
          }
          return saveShareInfoV2(params)
            .then((result) => {
              if (!result.success) {
                return Platform.notification({
                  title: i18n.t('common.base.tip.saveFail'),
                  type: 'error',
                  message: result.message,
                })
              }
              
              Platform.notification({
                title: SAVE_SUCCESS,
                type: 'success',
                message: i18n.t('common.base.tip.saveSuccess'),
              })

              // getPartalShareInfo();
              if (isDownload) downloadPoster();
            })
            .catch((error) => {
              console.warn(error);
            });
        } 
      });
    };

    watch(
      () => state.shareForm.shareTitle,
      () => {
        if(!state.shareForm.setting.shareTitleLanguage?.[i18n.locale]){
          state.shareForm.setting.shareTitleLanguage[i18n.locale] = ''
        }
        if(state.shareForm.shareTitle && state.shareForm.shareTitle !== state.shareForm.setting.shareTitleLanguage[i18n.locale]){
          state.shareForm.setting.shareTitleLanguage[i18n.locale] = state.shareForm.shareTitle
        }
      }
    );

    watch(
      () => state.shareForm.shareDescribe,
      () => {
        if(!state.shareForm.setting.shareDescribeLanguage?.[i18n.locale]){
          state.shareForm.setting.shareDescribeLanguage[i18n.locale] = ''
        }
        if(state.shareForm.shareDescribe && state.shareForm.shareDescribe !== state.shareForm.setting.shareDescribeLanguage[i18n.locale]){
          state.shareForm.setting.shareDescribeLanguage[i18n.locale] = state.shareForm.shareDescribe
        }
      }
    );

    return {
      ...toRefs(state),
      shareFormRef,
      portalShareRef,
      openDialog,
      downloadQrcode,
      downloadPoster,
      onBeforeUploadImage,
      uploadImagePic,
      saveConfig,
      handleClickCopyShareUrl,
      updateTitleLanguage,
      updateDescribeLanguage,
      isMultiLanguage,
    };
  },
};
</script>

<style lang="scss" scoped>
@import "../index";

.share-dialog-container {
  .share-dialog-container-header {
    display: flex;
    align-items: center;
    @include box-setting(100%, 64px, #ffffff);
    box-shadow: 0px 9px 28px 8px rgba(0, 0, 0, 0.05),
      0px 6px 16px 0px rgba(0, 0, 0, 0.08), 0px 3px 6px -4px rgba(0, 0, 0, 0.12);
    padding: 0 16px;
    margin-bottom: 20px;

    span {
      @include font-setting(14px, 400, #595959, 22px);
    }

    .share-seeting-header-button {
      @include font-setting(14px, 400, $color-primary-light-6, 22px);
      margin-left: 17px;
      cursor: pointer;
    }

    .share-setting-header-input {
      width: 306px;
      margin: 0 25px 0 16px;
    }
  }

  .share-dialog-container-main {
    width: 100%;
    height: 504px;
    padding: 12px 20px;

    h3 {
      @include font-setting(14px, 400, #595959, 22px);
    }

    .share-dialog-style-view {
      display: flex;
      justify-content: center;

      .share-dialog-style-box {
        // width: 260px;
        height: 440px;
        margin-right: 36px;
      }

      .share-dialog-style-config {
        width: 312px;

        .el-radio {
          margin-right: 0;
          margin-left: 16px;
        }

        .share-form-item {
          display: flex;
        }

        .share-dialog-style-upload {
          .share-image-uploader {
            width: 56px;
            height: 56px;
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            text-align: center;
            margin: 0;
            position: relative;
          }
          .share-image-uploader:hover {
            border-color: $color-primary-light-6;
          }
          .share-uploader-icon {
            font-size: 16px;
            color: #8c939d;
            width: 100%;
            height: 100%;
            line-height: 56px;
            text-align: center;
          }
          .share-style-image {
            width: 54px;
            height: 54px;
            display: block;
          }

          span {
            @include font-setting(12px, 400, #8c8c8c, 20px);
            position: absolute;
            top: 5px;
            left: 68px;
          }
        }

        .share-dialog-style-button {
          margin: 80px 0 0 10px;
        }
      }
    }
  }
}

::v-deep .el-input-group__append,
.el-input-group__prepend {
  border-radius: 0 4px 4px 0;
}
.share-setting-header-input ::v-deep .el-input__inner {
  color: #bfbfbf !important;
}
.share-dialog-style-textarea ::v-deep .el-textarea__inner {
  color: #595959 !important;
  resize: none;
}
.share-dialog ::v-deep .el-dialog__body {
  padding: 0 !important;
}
</style>
